<?php
session_start();
if(!isset($_SESSION)) die("you want logging");
include_once "configure.php";

header('Content-type: text/html; charset=UTF-8'); 

//function json_encode for php4
if (!function_exists('json_encode'))
{
  function json_encode($a=false)
  {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a))
    {
      if (is_float($a))
      {
        // Always use "." for floats.
        return floatval(str_replace(",", ".", strval($a)));
      }

      if (is_string($a))
      {
        static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
      }
      else
        return $a;
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a))
    {
      if (key($a) !== $i)
      {
        $isList = false;
        break;
      }
    }
    $result = array();
    if ($isList)
    {
      foreach ($a as $v) $result[] = json_encode($v);
      return '[' . join(',', $result) . ']';
    }
    else
    {
      foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return '{' . join(',', $result) . '}';
    }
  }
}

function echo_pre($array){
	echo "<pre>";
	print_r($array);
	echo "</pre>";
}

//unserialize for UTF8
function mb_unserialize($serial_str) {
	$out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
	return unserialize($out);
} 

function debugSql($string){
	$myFile = "debug.txt";
	$fh = fopen($myFile, 'a+') or die("can't open file");
	fwrite($fh, $string."\n\r");
	fclose($fh);
}

if($unicode_or_utf8=="utf8"){
	//UTF8
	$arra_data =mb_unserialize(base64_decode($_GET['values']));
}else{
	//Unicode
	$arra_data =unserialize(base64_decode($_GET['values']));
}

//die(echo_pre($arra_data));

foreach($arra_data as $item){
	//Vérifier les paramèttres
	if(empty($_GET['id_key']) or empty($item[0]) or empty($_GET['type']) or (empty($item[1]) && $item[1]!=0) or empty($item[2]) ){
		die("Fatal Error!");
		exit;
	}
}
	
//Connexion à la base de données
$connect= mysql_connect(DB_SERVEUR,DB_USER,DB_PASS);

@mysql_query("SET NAMES 'utf8'");
@mysql_query("SET CHARACTER SET utf8");

mysql_select_db(DB_BDD) or die("erreur de connexion a la base de donnees");

//Valider l'action
foreach($arra_data as $item){
	$sql_isvalid="SELECT `id_status`,`translation`,`id_key`,`id_user_trans`
				  FROM `translation`
				  WHERE `id_key`=".$_GET['id_key']." 
				  AND `id_lang`=".$item[0].";";
				  
	$SqlStr= mysql_query($sql_isvalid) or die(mysql_error());	
	$rows = mysql_fetch_row ($SqlStr);
}

$type=$_GET['type'];
$without_propagation=$_GET['without_propagation'];

//Save with propagation
/*if($without_propagation=='false'){*/

	//Get key_name US
	$sql_get_duplicate="SELECT t.`translation`, k.`key_name`
						 FROM `translation` t
						 JOIN `keys` as k ON k.`id_key`=t.`id_key`
						 WHERE t.`id_lang`=1 
						   AND t.`id_key`=".$_GET['id_key'];
	
	$rs_get_duplicate= mysql_query($sql_get_duplicate) or die(mysql_error());
	$rows_get_duplicate = mysql_fetch_row ($rs_get_duplicate);
	
	//Trouver les keys identiques  
	if($rows_get_duplicate[0]!=""){
		//N'appliquer la propagation que aux clés US validées.
		$select_all_idem="SELECT t.`id_key` 
						  FROM `translation` t
						  WHERE t.`id_lang`=1
						  AND t.`id_status`=2
						  AND t.`translation` LIKE '".mysql_real_escape_string($rows_get_duplicate[0])."'";
	}
	/*else{
		//Chaine US sans traduction, trouver les id_keys par KeyName avec une traduction vide.
		$select_all_idem="SELECT t.`id_key` 
						  FROM `translation` t
						  JOIN `keys` as k ON k.`id_key`=t.`id_key`
						  WHERE t.`id_lang`=1		  
						    AND t.`translation` ='' 
						    AND k.`key_name` LIKE '".mysql_real_escape_string($rows_get_duplicate[1])."'";
	}*/
	
	if($select_all_idem!=""){
		//Make list ids_keys (1,2,3,...)
		$SqlStr = mysql_query($select_all_idem);
		$i=0;
		while ($rang=mysql_fetch_array($SqlStr)){
			if($i==0){
				$MarqueId = $rang['id_key'];
			}else{
				$MarqueId.=",".$rang['id_key'];
			}
			$i++;
		}		
	}

	if($MarqueId=="," || $MarqueId==""){
		$MarqueId=$_GET['id_key'];
	}
	
//Without propagation		
/*}elseif($without_propagation=='true'){
	$MarqueId=$_GET['id_key'];
}*/

$return_arr=array();

//Pour chaque langue
foreach($arra_data as $item){
	//action Update et Translation
	if($rows[0]==0 || $rows[0]==1){
		$sql = 'UPDATE `translation` ';
		
		if($unicode_or_utf8=="utf8"){
			//UTF8		
			$sql .= ' SET `translation`.`translation`="'.stripslashes(mysql_real_escape_string($item[1])).'" , ';
		}else{
			//Unicode
			$item[1]=str_replace("%u","&#x",$item[1]);
			$item[1]=str_replace('~~~more~~','+',urldecode(str_replace("+","~~~more~~",$item[1])));
			
			$sql .= ' SET `translation`.`translation`="'.mysql_real_escape_string(utf8_encode($item[1])).'", ';
		}
		
		$sql .=			' `translation`.`date`=NOW(), 
					  	`translation`.`id_status`='.intval($item[2]);
		//Traduction
		if(intval($rows[3])==0){
			//First translation=>Empty key
			$sql .= ' , `translation`.`id_user_trans`='.intval($_SESSION['id_user']->id_user);
			//Appliquer la propagation uniquement aux chaines vides
			$sql .= ' WHERE ( `translation`.`id_key`='.$_GET['id_key'].' OR 
								(
								 `translation`.`id_key` IN ('.$MarqueId.') 
								 	AND 
								 `translation`.`translation`=""
								 	AND
								 `translation`.`id_status`=0
								) 
							) ';
		}else{
			//Edited translation
			$sql .= ' , `translation`.`id_editor`='.intval($_SESSION['id_user']->id_user);
			$sql .= ' WHERE `translation`.`id_key`='.$_GET['id_key'];
		}
		
		$sql .= ' AND `translation`.`id_lang`='.intval($item[0]).";";

		//Debug requetes
		//debugSql($sql);		
		//die($sql);
		mysql_query($sql) or die(mysql_error());
	}
	
	//En cas d'erreur
	$requete_retour="SELECT t.id_status, t.translation, u.email, t.id_lang
					 FROM translation t
					 LEFT JOIN users as u ON t.id_user_trans=u.id_user
					 WHERE t.id_key=".$_GET['id_key']." 
					 AND t.id_lang=".$item[0];					 
	
	$get_value_from_data=mysql_query($requete_retour)or die(mysql_error());	
	$return_arr[]=mysql_fetch_row ($get_value_from_data);
}
		
mysql_close();
die(json_encode($return_arr));	
?>